/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package theserver;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Emma
 */
public class Controller implements Runnable {

    private int port;
    private ServerSocketConnection ssc;
    private DBConnection dBConnection;
    private ConnectToDevice connectToDevice;
    private Thread thread = new Thread(this);

    public Controller(int port) {
        this.port = port;
        ssc = new ServerSocketConnection(port, this);
        dBConnection = new DBConnection();
        connectToDevice = new ConnectToDevice();
        thread.start();
        System.err.println("Servern uppe lyssnar på port: "+ port);
    }

    public int checkIn(DeviceInfo c) {
        DeviceInfo clm = c;
        int inlogg = dBConnection.checkIn(clm);
        VenueList ven = dBConnection.getActivitiesForVenues(inlogg);
        connectToDevice.Connect(ven, c.getIpAddress(), c.getPort());
        return inlogg;
    }

    public DeviceList getConnectedDevices() {
        //gå igenom ArrayListan skapasocketar mot alla och skicka den till alla utan
        //att de själv är med, men objektet c är med
        DeviceList div = new DeviceList();
        div = (DeviceList) dBConnection.getAllConnectedDevices();
        return div;
    }

    public void run() {
        ArrayList<DeviceList> oldList = null;
        ArrayList<DeviceList> newList = null;
        while (true) {
            newList = dBConnection.getAllDevicesForLocation();
            if(oldList != null){
                if(oldList.size()==newList.size()){
                    for (int i = 0; i < newList.size(); i++) {
                        if(newList.get(i).containsAll(oldList.get(i))){
                         if(newList.get(i).size()!= oldList.get(i).size()){
                         connectToDevice.Connect(newList);
                         }
                        }
                        else{
                        connectToDevice.Connect(newList);
                        }

                    }
                }
                else{
                connectToDevice.Connect(newList);
                }
                oldList = newList;
            }
            else{
            connectToDevice.Connect(newList);
            }
            //connectToDevice.Connect(dBConnection.getAllDevicesForLocation());
            try {
                thread.sleep(60000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
